package cn.zhou.student.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.sql.DataSource;


@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 自定义用户授权管理
        http.authorizeRequests()
                .antMatchers("/login","/student/getConditionPageStudent").permitAll()
                // 需要对static文件夹下静态资源进行统一放行
                .antMatchers("/js/**","/css/**","/images/**","/fonts/**",
                        "/**/*.png","/**/*.jpg","/layer/**","/page").permitAll()
                .antMatchers("/login/**").permitAll()
                .anyRequest().authenticated();
        // 自定义用户登录控制
        http.formLogin()
                .loginPage("/login").permitAll()
//                .defaultSuccessUrl("/first.html")
                .defaultSuccessUrl("/student/getConditionPageStudent")
                .usernameParameter("username").passwordParameter("password")
                .failureUrl("/login?error=1");








    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //  密码需要设置编码器
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();


//        // 2、使用JDBC进行身份认证
        String userSQL ="select username,password,valid from admin " +
                "where username = ?";
        String authoritySQL="select username,authority from admin where username=?";
        auth.jdbcAuthentication().passwordEncoder(encoder)
                .dataSource(dataSource)
                .usersByUsernameQuery(userSQL)
                .authoritiesByUsernameQuery(authoritySQL);

    }

}
